package com.stool.nettyupload.server;

import com.stool.nettyupload.config.ResourceConfig;
import com.stool.nettyupload.exception.UploadException;
import com.stool.nettyupload.pojo.FileMessage;
import com.stool.nettyupload.utils.JsonUtils;
import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import io.netty.handler.codec.http.*;
import io.netty.handler.codec.http.multipart.*;
import io.netty.handler.codec.http.multipart.HttpPostRequestDecoder.EndOfDataDecoderException;
import io.netty.handler.codec.http.multipart.HttpPostRequestDecoder.ErrorDataDecoderException;
import io.netty.handler.codec.http.multipart.InterfaceHttpData.HttpDataType;
import io.netty.util.CharsetUtil;
import io.netty.util.ReferenceCountUtil;
import org.n3r.idworker.Id;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

import static io.netty.buffer.Unpooled.copiedBuffer;

public class HttpUploadServerHandler extends SimpleChannelInboundHandler<HttpObject> {

    private static final Integer USER_AVATAR = 0, PLAYLIST_COVER = 1, ALBUM_COVER = 2, SINGER_COVER = 3, SONG = 4;

    // 文件服务器主路径
    private String rootPath;

    private static final Logger logger = Logger.getLogger(HttpUploadServerHandler.class.getName());

    private HttpRequest request;

    private boolean readingChunks;

    private HttpData partialContent;

//    private final StringBuilder responseContent = new StringBuilder();

    private static final HttpDataFactory factory =
            new DefaultHttpDataFactory(DefaultHttpDataFactory.MINSIZE); // Disk if size exceed

    private HttpPostRequestDecoder decoder;

    // 文件名
    private String filename;
    // 文件类型：0：用户头像；1：歌单封面；2：专辑封面；3：歌曲
    private Integer fileType;

    static {
        DiskFileUpload.deleteOnExitTemporaryFile = true; // should delete file  删除临时文件（正常情况下）
        // on exit (in normal
        // exit)
        DiskFileUpload.baseDirectory = null; // system temp directory   系统临时文件所在文件夹
        DiskAttribute.deleteOnExitTemporaryFile = true; // should delete file on 删除临时文件（正常情况下）
        // exit (in normal exit)
        DiskAttribute.baseDirectory = null; // system temp directory 系统临时文件所在文件夹
    }

    public HttpUploadServerHandler(String rootPath) {
        this.rootPath = rootPath;
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        // 如果编码器不为空，删除当前请求对应的所有HttpData（在磁盘上）
        if (decoder != null) {
            decoder.cleanFiles();
        }
    }

    @Override
    public void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
        if (msg instanceof HttpRequest) {
            HttpRequest request = this.request = (HttpRequest) msg;
            URI uri = new URI(request.uri());
            if (!uri.getPath().startsWith("/form")) {
                // Write Menu   如果请求路径不以/form开头，返回错误信息
                writeJsonResponse(ctx, JsonUtils.errorJson("路径错误"));
                return;
            }


            // 得到路径请求参数
            QueryStringDecoder decoderQuery = new QueryStringDecoder(request.uri());
            Map<String, List<String>> uriAttributes = decoderQuery.parameters();

            if (uriAttributes.get("fileType") == null) {
                writeJsonResponse(ctx, JsonUtils.errorJson("参数缺失"));
                return;
            } else {
                fileType = Integer.parseInt(uriAttributes.get("fileType").get(0));
//                filename = uriAttributes.get("filename").get(0);
                logger.info("fileType:" + fileType);
//                logger.info("filename:" + filename);
            }
            // 如果是GET，直接返回
            if (request.method().equals(HttpMethod.GET)) {
                writeJsonResponse(ctx, JsonUtils.errorJson("必须是POST，不能为GET"));
                return;
            }
            try {
                decoder = new HttpPostRequestDecoder(factory, request);
            } catch (ErrorDataDecoderException e1) {
                e1.printStackTrace();
                writeJsonResponse(ctx, JsonUtils.errorJson(e1.getMessage()));
                ctx.channel().close();
                return;
            }
            // 判断是否是chunk 分块传输
            readingChunks = HttpUtil.isTransferEncodingChunked(request);
            logger.info("Is Chunked: " + readingChunks + "\r\n");
            logger.info("IsMultipart: " + decoder.isMultipart() + "\r\n");
            if (readingChunks) {
                // Chunk version
                readingChunks = true;
            }
        }

        // check if the decoder was constructed before
        // if not it handles the form get
        if (decoder != null) {
            if (msg instanceof HttpContent) {
                // New chunk is received 接收新的chunk
                HttpContent chunk = (HttpContent) msg;
                try {
                    decoder.offer(chunk);
                } catch (ErrorDataDecoderException e1) {
                    e1.printStackTrace();
                    writeJsonResponse(ctx, JsonUtils.errorJson(e1.getMessage()));
                    ctx.channel().close();
                    return;
                }
                // example of reading chunk by chunk (minimize memory usage due to
                // Factory)
                try {
                    readHttpDataChunkByChunk();
                } catch (UploadException e) {
                    // 异常处理
                    writeJsonResponse(ctx, JsonUtils.errorJson(e.getMessage()));
                    ctx.channel().close();
                }

                // example of reading only if at the end
                if (chunk instanceof LastHttpContent) {
                    // 读到了最后，返回正确
                    FileMessage fileMessage = new FileMessage();
                    fileMessage.setName(filename);
                    writeJsonResponse(ctx, JsonUtils.okJson(fileMessage));
                    readingChunks = false;
                    reset();
                }
            }
        } else {
            writeJsonResponse(ctx, JsonUtils.errorJson("未知错误"));
        }
    }

    private void reset() {
        request = null;

        // destroy the decoder to release all resources
        ReferenceCountUtil.retain(decoder); // fix
        decoder.destroy();
        decoder = null;
    }

    /**
     * Example of reading request by chunk and getting values from chunk to chunk
     */
    private void readHttpDataChunkByChunk() {
        try {
            while (decoder.hasNext()) {
                InterfaceHttpData data = decoder.next();
                if (data != null) {
                    // check if current HttpData is a FileUpload and previously set as partial
                    if (partialContent == data) {
                        logger.info(" 100% (FinalSize: " + partialContent.length() + ")");
                        partialContent = null;
                    }
                    try {
                        // new value
                        writeHttpData(data);
                    } finally {
//                        data.release(); fix
                    }
                }
            }
            // Check partial decoding for a FileUpload
            InterfaceHttpData data = decoder.currentPartialHttpData();
            if (data != null) {
                StringBuilder builder = new StringBuilder();
                if (partialContent == null) {
                    partialContent = (HttpData) data;
                    if (partialContent instanceof FileUpload) {
                        builder.append("Start FileUpload: ")
                                .append(((FileUpload) partialContent).getFilename()).append(" ");
                    } else {
                        builder.append("Start Attribute: ")
                                .append(partialContent.getName()).append(" ");
                    }
                    builder.append("(DefinedSize: ").append(partialContent.definedLength()).append(")");
                }
                if (partialContent.definedLength() > 0) {
                    builder.append(" ").append(partialContent.length() * 100 / partialContent.definedLength())
                            .append("% ");
                    logger.info(builder.toString());
                } else {
                    builder.append(" ").append(partialContent.length()).append(" ");
                    logger.info(builder.toString());
                }
            }
        } catch (EndOfDataDecoderException e1) {
            // end
//            responseContent.append("\r\n\r\nEND OF CONTENT CHUNK BY CHUNK\r\n\r\n");
            logger.info("END OF CONTENT CHUNK BY CHUNK");
        }
    }

    private void writeHttpData(InterfaceHttpData data) {
        if (data.getHttpDataType() == HttpDataType.Attribute) {
            Attribute attribute = (Attribute) data;
            String value;
            try {
                value = attribute.getValue();
            } catch (IOException e1) {
                e1.printStackTrace();
                throw new UploadException(e1.getMessage());
//                return;
            }
            logger.info("\r\nBODY Attribute: " + attribute.getHttpDataType().name() + ": "
                    + attribute + "\r\n");
            logger.info("key:" + attribute.getName() + "," + "value:" + value);

        } else {
            logger.info("BODY FileUpload: " + data.getHttpDataType().name() + ": " + data);
            if (data.getHttpDataType() == HttpDataType.FileUpload) {
                filename = getNewFilename();    // 得到文件名
                FileUpload fileUpload = (FileUpload) data;
                if (fileUpload.isCompleted()) {
                    // fileUpload.isInMemory();// tells if the file is in Memory
                    // or on File
                    // fileUpload.renameTo(dest); // enable to move into another
                    // File dest
                    // decoder.removeFileUploadFromClean(fileUpload); //remove
                    // the File of to delete file
                    File dir = new File(getDirPath());
                    if (!dir.exists()) {
                        dir.mkdirs();
                    }
                    File dest = new File(dir, filename);
                    try {
                        fileUpload.renameTo(dest);
                    } catch (IOException e) {
                        e.printStackTrace();
                        throw new UploadException(e.getMessage());
                    }

                } else {
                    logger.info("File to be continued but should not!");
                }
            }
        }
    }

    private void writeJsonResponse(ChannelHandlerContext ctx, String json) {
        // Decide whether to close the connection or not.
        boolean close = request.headers().contains(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE, true)
                || request.protocolVersion().equals(HttpVersion.HTTP_1_0)
                && !request.headers().contains(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE, true);

        ByteBuf buf = copiedBuffer(json, CharsetUtil.UTF_8);
        // Build the response object.
        FullHttpResponse response = new DefaultFullHttpResponse(
                HttpVersion.HTTP_1_1, HttpResponseStatus.OK, buf);

        response.headers().set(HttpHeaderNames.CONTENT_TYPE, "application/json; charset=UTF-8");
        response.headers().setInt(HttpHeaderNames.CONTENT_LENGTH, buf.readableBytes());

        // Write the response.
        ChannelFuture future = ctx.channel().writeAndFlush(response);
        // Close the connection after the write operation is done if necessary.
        if (close) {
            future.addListener(ChannelFutureListener.CLOSE);
        }
    }


    private String getDirPath() {
        String path = rootPath;
        if (fileType.equals(USER_AVATAR)) {
            path = path + "avatar/";
        } else if (fileType.equals(PLAYLIST_COVER)) {
            path = path + "cover/playlist/";
        } else if (fileType.equals(ALBUM_COVER)) {
            path = path + "cover/album/";
        } else if (fileType.equals(SINGER_COVER)) {
            path = path + "cover/singer/";
        } else if (fileType.equals(SONG)) {
            path = path + "song/";
        }
        return path;
    }

    private String getNewFilename() {
        String filename = Id.nextString();
        if (fileType.equals(SONG)) {
            filename = filename + ".mp3";
        } else {
            filename = filename + ".jpg";
        }
        return filename;
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        logger.log(Level.WARNING, "response error", cause);
        ctx.channel().close();
    }
}